package org.jeecg.modules.operations.assistant.crm.controller;

import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.operations.assistant.crm.entity.*;
import org.jeecg.modules.operations.assistant.crm.service.*;
import org.jeecg.modules.operations.assistant.crm.vo.CrmWorkOrderPage;
import org.jeecg.modules.operations.assistant.servicemanage.entity.ServiceUsers;
import org.jeecg.modules.operations.assistant.servicemanage.service.IServiceUsersService;
import org.jeecg.modules.operations.assistant.work.service.IWorkServiceRecordsService;
import org.jeecg.modules.operations.assistant.work.entity.*;
import org.jeecg.modules.operations.assistant.work.service.*;
import org.jeecg.modules.system.controller.SysAnnouncementController;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.operations.assistant.work.vo.WorkOrderPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 工单信息
 * @Author: jeecg-boot
 * @Date:   2024-01-07
 * @Version: V1.0
 */
@Api(tags="工单信息")
@RestController
@RequestMapping("/crm/workOrder")
@Slf4j
public class CrmWorkOrderController {
	@Autowired
	private ICrmWorkOrderService workOrderService;
	@Autowired
	private ICrmInstallationOrderService installationOrderService;
	@Autowired
	private ICrmMaintainOrdersService maintainOrdersService;
	@Autowired
	private ICrmWorkOrderProcessService workOrderProcessService;
	@Autowired
	private IServiceUsersService serviceUsersService;
	@Autowired
	private ICrmAttendanceRecordService attendanceRecordService;
	@Autowired
	private ICrmWorkServiceRecordsService workServiceRecordsService;
	@Autowired
	private ICrmWorkOrderReceiptService workOrderReceiptService;
	@Autowired
	private ICrmFollowUpService followUpService;
	@Resource
	private WebSocket webSocket;

	@Autowired
	private ISysUserService sysUserService;

	 @Resource
	 SysAnnouncementController sysAnnouncementController;

	 @Autowired
	 private ISysAnnouncementService sysAnnouncementService;

	/**
	 * 分页列表查询
	 *
	 * @param workOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "工单信息-分页列表查询")
	@ApiOperation(value="工单信息-分页列表查询", notes="工单信息-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="qperationsAssistant/index")
	public Result<IPage<CrmWorkOrder>> queryPageList(CrmWorkOrder workOrder,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		QueryWrapper<CrmWorkOrder> queryWrapper = QueryGenerator.initQueryWrapper(workOrder, req.getParameterMap());
		Page<CrmWorkOrder> page = new Page<CrmWorkOrder>(pageNo, pageSize);
		IPage<CrmWorkOrder> pageList = workOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param workOrderPage
	 * @return
	 */
	@AutoLog(value = "工单信息-添加")
	@ApiOperation(value="工单信息-添加", notes="工单信息-添加")
    @RequiresPermissions("work:work_order:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CrmWorkOrderPage workOrderPage,
							  HttpServletRequest req) {
		CrmWorkOrder workOrder = new CrmWorkOrder();
		BeanUtils.copyProperties(workOrderPage, workOrder);
		String titile = ""; // 通知公告标题
		SysUser user = null; // 通知用户
		if(workOrder.getServiceStaff() == null) {
			System.out.println("workOrder.getHomeAddress()="+workOrder.getHomeAddress());
			ServiceUsers serviceUsers = new ServiceUsers();
			serviceUsers.setServiceArea("*"+workOrder.getHomeAddress());
			Map<String, String[]> parameterMap = new HashMap<>();
			QueryWrapper<ServiceUsers> queryWrapper = QueryGenerator.initQueryWrapper(serviceUsers, parameterMap);
			queryWrapper.eq("status", 1);
			Page<ServiceUsers> page = new Page<ServiceUsers>(1, 10);
			IPage<ServiceUsers> pageList = serviceUsersService.page(page, queryWrapper);
			if(pageList.getRecords().size() > 0){
				// 创建Random对象
				Random random = new Random();
				// 生成0到2之间（包括0但不包括2）的随机数
				int randomNum = random.nextInt(pageList.getRecords().size());
				serviceUsers = pageList.getRecords().get(randomNum);
				workOrder.setServiceStaff(serviceUsers.getUser());
				List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
				CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
				workOrderProcess.setStatus(1);
				//获取登录用户信息
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				if(sysUser!=null){
					workOrderProcess.setContent(sysUser.getRealname()+"创建工单，工单描述："+workOrderPage.getDescription());
				}
				workOrderProcessList.add(workOrderProcess);
				workOrderProcess = new CrmWorkOrderProcess();
				workOrderProcess.setStatus(2);
				workOrderProcess.setContent("系统将工单指派给"+serviceUsers.getUser());
				workOrderProcessList.add(workOrderProcess);
				workOrderPage.setWorkOrderProcessList(workOrderProcessList);

				//通过传入信息查询新的用户信息
				SysUser sysUsers = new SysUser();
				sysUsers.setUsername(serviceUsers.getUser());
				user = sysUserService.getOne(new QueryWrapper<SysUser>(sysUsers));
				if (user != null) {
					//获取登录用户信息
//					LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//					SysAnnouncement sysAnnouncement = new SysAnnouncement();
//					sysAnnouncement.setMsgCategory("1");
//					sysAnnouncement.setTitile(sysUser.getRealname()+"创建了工单，请尽快去接单。");
//					sysAnnouncement.setMsgAbstract(sysUser.getRealname()+"创建了工单，请尽快去接单。");
//					sysAnnouncement.setMsgType("USER");
//					sysAnnouncement.setPriority("H");
//					sysAnnouncement.setUserIds(user.getId()+","+loginUser.getId());
//					sysAnnouncementController.add(sysAnnouncement);
					System.out.println("useruser==="+user.getUsername()+":id"+user.getId());
//					JSONObject obj = new JSONObject();
//					Date refDate = new Date();
//					obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
//					obj.put(WebsocketConst.MSG_ID, refDate.getTime());
//					obj.put(WebsocketConst.MSG_TXT, sysUser.getRealname()+"创建了工单，请尽快去接单。");
//					webSocket.sendMessage(user.getId(), obj.toJSONString());
				}
			}else {
				return Result.error("该区域无上门师傅，请手工选择服务人员。");
			}

		}else {
			List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
			CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
			workOrderProcess.setStatus(1);
			//获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			if(sysUser!=null){
				workOrderProcess.setContent(sysUser.getRealname()+"创建工单，工单描述："+workOrderPage.getDescription());
			}
			workOrderProcessList.add(workOrderProcess);
			workOrderProcess = new CrmWorkOrderProcess();
			workOrderProcess.setStatus(2);
			workOrderProcess.setContent("系统将工单指派给"+workOrder.getServiceStaff());
			workOrderProcessList.add(workOrderProcess);
			workOrderPage.setWorkOrderProcessList(workOrderProcessList);

			user = sysUserService.getUserByName(workOrder.getServiceStaff());
//			SysUser sysUserById = sysUserService.getById(sysUser.getId());
//			Date refDate = new Date();
//			JSONObject obj = new JSONObject();
//			obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
//			obj.put(WebsocketConst.MSG_ID, refDate.getTime());
//			obj.put(WebsocketConst.MSG_TXT, sysUser.getRealname()+"创建了工单，请尽快去接单。");
//			webSocket.sendMessage(user.getId(), obj.toJSONString());
		}
		// 2.插入用户通告阅读标记表记录
		//获取登录用户信息
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		// 创建通知公告
		SysAnnouncement sysAnnouncement = new SysAnnouncement();
		sysAnnouncement.setMsgCategory("1");
		sysAnnouncement.setTitile(loginUser.getRealname()+"创建了工单，请尽快去接单。");
		sysAnnouncement.setMsgAbstract(loginUser.getRealname()+"创建了工单，请尽快去接单。");
		sysAnnouncement.setMsgType("USER");
		sysAnnouncement.setPriority("H");
		sysAnnouncement.setUserIds(user.getId()+","+loginUser.getId());
		sysAnnouncementController.add(sysAnnouncement);
		// 查询通知公告
//		column=createTime&order=desc&pageNo=1&pageSize=10&_t=1721233416605
		sysAnnouncement = new SysAnnouncement();
		//是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
		if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
			sysAnnouncement.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
		}
		sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
		sysAnnouncement.setSendStatus(CommonConstant.DEL_FLAG_0.toString());
		Map<String, String[]> parameterMap = new HashMap<>();
		QueryWrapper<SysAnnouncement> queryWrapper = QueryGenerator.initQueryWrapper(sysAnnouncement, parameterMap);
//		queryWrapper.eq("status", 1);
		Page<SysAnnouncement> page = new Page<SysAnnouncement>(1, 10);
		IPage<SysAnnouncement> pageList = sysAnnouncementService.page(page, queryWrapper);

//		Result<IPage<SysAnnouncement>> result = sysAnnouncementController.queryPageList(sysAnnouncement,1,10,req);

		for(SysAnnouncement announcement : pageList.getRecords()){
			sysAnnouncementController.doReleaseData(announcement.getId(),req);
		}

//		Date refDate = new Date();
//		JSONObject obj = new JSONObject();
//		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
//		obj.put(WebsocketConst.MSG_ID, refDate.getTime());
//		obj.put(WebsocketConst.MSG_TXT, loginUser.getRealname()+"创建了工单，请尽快去接单。");
//		webSocket.sendMessage(loginUser.getId(), obj.toJSONString());
		workOrderService.saveMain(workOrder, workOrderPage.getInstallationOrderList(),workOrderPage.getMaintainOrdersList(),workOrderPage.getWorkOrderProcessList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param workOrderPage
	 * @return
	 */
	@AutoLog(value = "工单信息-编辑")
	@ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
    @RequiresPermissions("work:work_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CrmWorkOrderPage workOrderPage) {
		CrmWorkOrder workOrder = new CrmWorkOrder();
		BeanUtils.copyProperties(workOrderPage, workOrder);
		CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		if(workOrderEntity==null) {
			return Result.error("未找到对应数据");
		}
		workOrderService.updateMain(workOrder, workOrderPage.getInstallationOrderList(),workOrderPage.getMaintainOrdersList(),workOrderPage.getWorkOrderProcessList(),workOrderPage.getAttendanceRecordList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工单信息-通过id删除")
	@ApiOperation(value="工单信息-通过id删除", notes="工单信息-通过id删除")
    @RequiresPermissions("work:work_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		workOrderService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "工单信息-批量删除")
	@ApiOperation(value="工单信息-批量删除", notes="工单信息-批量删除")
    @RequiresPermissions("work:work_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.workOrderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "工单信息-通过id查询")
	@ApiOperation(value="工单信息-通过id查询", notes="工单信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CrmWorkOrder> queryById(@RequestParam(name="id",required=true) String id) {
		CrmWorkOrder workOrder = workOrderService.getById(id);
		if(workOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(workOrder);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "安装订单-通过主表ID查询")
	@ApiOperation(value="安装订单-通过主表ID查询", notes="安装订单-通过主表ID查询")
	@GetMapping(value = "/queryInstallationOrderByMainId")
	public Result<IPage<CrmInstallationOrder>> queryInstallationOrderListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CrmInstallationOrder> installationOrderList = installationOrderService.selectByMainId(id);
		IPage <CrmInstallationOrder> page = new Page<>();
		page.setRecords(installationOrderList);
		page.setTotal(installationOrderList.size());
		return Result.OK(page);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "维护订单-通过主表ID查询")
	@ApiOperation(value="维护订单-通过主表ID查询", notes="维护订单-通过主表ID查询")
	@GetMapping(value = "/queryMaintainOrdersByMainId")
	public Result<IPage<CrmMaintainOrders>> queryMaintainOrdersListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CrmMaintainOrders> maintainOrdersList = maintainOrdersService.selectByMainId(id);
		IPage <CrmMaintainOrders> page = new Page<>();
		page.setRecords(maintainOrdersList);
		page.setTotal(maintainOrdersList.size());
		return Result.OK(page);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "工单流程-通过主表ID查询")
	@ApiOperation(value="工单流程-通过主表ID查询", notes="工单流程-通过主表ID查询")
	@GetMapping(value = "/queryWorkOrderProcessByMainId")
	public Result<IPage<CrmWorkOrderProcess>> queryWorkOrderProcessListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CrmWorkOrderProcess> workOrderProcessList = workOrderProcessService.selectByMainId(id);
		IPage <CrmWorkOrderProcess> page = new Page<>();
		page.setRecords(workOrderProcessList);
		page.setTotal(workOrderProcessList.size());
		return Result.OK(page);
	}
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "签到记录-通过主表ID查询")
	 @ApiOperation(value="签到记录-通过主表ID查询", notes="签到记录-通过主表ID查询")
	 @GetMapping(value = "/queryAttendanceRecordByMainId")
	 public Result<IPage<CrmAttendanceRecord>> queryAttendanceRecordListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<CrmAttendanceRecord> attendanceRecordList = attendanceRecordService.selectByMainId(id);
		 IPage <CrmAttendanceRecord> page = new Page<>();
		 page.setRecords(attendanceRecordList);
		 page.setTotal(attendanceRecordList.size());
		 return Result.OK(page);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param workOrder
    */
    @RequiresPermissions("work:work_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CrmWorkOrder workOrder) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CrmWorkOrder> queryWrapper = QueryGenerator.initQueryWrapper(workOrder, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CrmWorkOrder>  workOrderList = workOrderService.list(queryWrapper);

      // Step.3 组装pageList
      List<CrmWorkOrderPage> pageList = new ArrayList<CrmWorkOrderPage>();
      for (CrmWorkOrder main : workOrderList) {
		  CrmWorkOrderPage vo = new CrmWorkOrderPage();
          BeanUtils.copyProperties(main, vo);
          List<CrmInstallationOrder> installationOrderList = installationOrderService.selectByMainId(main.getId());
          vo.setInstallationOrderList(installationOrderList);
          List<CrmMaintainOrders> maintainOrdersList = maintainOrdersService.selectByMainId(main.getId());
          vo.setMaintainOrdersList(maintainOrdersList);
          /*List<WorkOrderProcess> workOrderProcessList = workOrderProcessService.selectByMainId(main.getId());
		  vo.setWorkOrderProcessList(workOrderProcessList);
		  List<AttendanceRecord> attendanceRecordList = attendanceRecordService.selectByMainId(main.getId());
		  vo.setAttendanceRecordList(attendanceRecordList);
		  List<WorkServiceRecords> workServiceRecordsList = workServiceRecordsService.selectByMainId(main.getId());
		  vo.setWorkServiceRecordsList(workServiceRecordsList);*/
		  List<CrmWorkOrderReceipt> workOrderReceiptList = workOrderReceiptService.selectByMainId(main.getId());
		  vo.setWorkOrderReceiptList(workOrderReceiptList);
		  /*List<FollowUp> followUpList = followUpService.selectByMainId(main.getId());
		  vo.setFollowUpList(followUpList);*/
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "工单信息列表");
      mv.addObject(NormalExcelConstants.CLASS, CrmWorkOrderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工单信息数据", "导出人:"+sysUser.getRealname(), "工单信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("work:work_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CrmWorkOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CrmWorkOrderPage.class, params);
              for (CrmWorkOrderPage page : list) {
				  CrmWorkOrder po = new CrmWorkOrder();
                  BeanUtils.copyProperties(page, po);
                  workOrderService.saveMain(po, page.getInstallationOrderList(),page.getMaintainOrdersList(),page.getWorkOrderProcessList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  *   通过id操作接单流程
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "工单信息-通过id操作接单流程")
	 @ApiOperation(value="工单信息-通过id操作接单流程", notes="工单信息-通过id操作接单流程")
	 @RequiresPermissions("work:work_order:receivingOrders")
//	 @DeleteMapping(value = "/receivingOrders")
	 @RequestMapping(value = "/receivingOrders", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> receivingOrders(@RequestParam(name="id",required=true) String id) {
//		 workOrderService.delMain(id);
		 CrmWorkOrder workOrder = workOrderService.getById(id);
		 // 已接单后将状态改为待预约
		 workOrder.setWorkOrderStatus(15);
		 CrmWorkOrderPage workOrderPage = new CrmWorkOrderPage();
//		 BeanUtils.copyProperties(workOrderPage, workOrder);

		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(3); // 已接单
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"已接单 电话："+sysUser.getPhone());
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateMain(workOrder,workOrderPage.getWorkOrderProcessList());
		 return Result.OK("接单成功!");
	 }

	 /**
	  *   通过id操作预约流程
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-通过id操作预约流程")
	 @ApiOperation(value="工单信息-通过id操作预约流程", notes="工单信息-通过id操作预约流程")
	 @RequiresPermissions("work:work_order:reservation")
//	 @DeleteMapping(value = "/receivingOrders")
	 @RequestMapping(value = "/reservation", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> reservation(@RequestBody CrmWorkOrderPage workOrderPage) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 // 待预约后将状态改为待签到
		 workOrder.setWorkOrderStatus(16);
//		 WorkOrderPage workOrderPage = new WorkOrderPage();
//		 BeanUtils.copyProperties(workOrderPage, workOrder);

		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(5); // 已预约
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"已预约客户");
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateMain(workOrder,workOrderPage.getWorkOrderProcessList());
		 return Result.OK("预约客户成功!");
	 }

	 /**
	  *   通过id操作签到流程
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-通过id操作签到流程")
	 @ApiOperation(value="工单信息-通过id操作签到流程", notes="工单信息-通过id操作签到流程")
	 @RequiresPermissions("work:work_order:signIn")
//	 @DeleteMapping(value = "/receivingOrders")
	 @RequestMapping(value = "/signIn", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> signIn(@RequestBody CrmWorkOrderPage workOrderPage) {
//		 workOrderService.delMain(id);
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 // 待签到后将状态改为待处理
		 workOrder.setWorkOrderStatus(17);
//		 WorkOrderPage workOrderPage = new WorkOrderPage();
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
//		 BeanUtils.copyProperties(workOrderPage, workOrder);

		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(4); // 已签到
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"签到，签到地点："+workOrderPage.getAttendanceRecordList().get(0).getFullAddress());
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateMain(workOrder,workOrderPage.getWorkOrderProcessList(),workOrderPage.getAttendanceRecordList());
		 return Result.OK("现场签到成功!");
	 }

	 /**
	  *   通过id操作处理流程
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "工单信息-通过id操作处理流程")
	 @ApiOperation(value="工单信息-通过id操作处理流程", notes="工单信息-通过id操作处理流程")
	 @RequiresPermissions("work:work_order:handle")
//	 @DeleteMapping(value = "/receivingOrders")
	 @RequestMapping(value = "/handle", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> handle(@RequestParam(name="id",required=true) String id) {
//		 workOrderService.delMain(id);
		 CrmWorkOrder workOrder = workOrderService.getById(id);
		 // 待处理后将状态改为待回访
		 workOrder.setWorkOrderStatus(12);
		 CrmWorkOrderPage workOrderPage = new CrmWorkOrderPage();
//		 BeanUtils.copyProperties(workOrderPage, workOrder);

		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(6); // 已处理
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"已处理");
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateMain(workOrder,workOrderPage.getWorkOrderProcessList());
		 return Result.OK("处理成功!");
	 }

	 /**
	  *  转派
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-编辑")
	 @ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
	 @RequiresPermissions("work:work_order:edit")
	 @RequestMapping(value = "/workOrderEdit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> workOrderEdit(@RequestBody CrmWorkOrderPage workOrderPage,
										 HttpServletRequest req) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(2); // 已派单
		 //获取登录用户信息
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(loginUser!=null){
			 workOrderProcess.setContent(loginUser.getRealname()+"把工单派给"+workOrder.getServiceStaff());
			 // 创建通知公告
			 SysAnnouncement sysAnnouncement = new SysAnnouncement();
			 sysAnnouncement.setMsgCategory("1");
			 sysAnnouncement.setTitile(loginUser.getRealname()+"把工单派给"+workOrder.getServiceStaff()+"，请尽快去接单。");
			 sysAnnouncement.setMsgAbstract(loginUser.getRealname()+"把工单派给"+workOrder.getServiceStaff()+"，请尽快去接单。");
			 sysAnnouncement.setMsgType("USER");
			 sysAnnouncement.setPriority("H");
			 SysUser user = sysUserService.getUserByName(workOrder.getServiceStaff());
			 sysAnnouncement.setUserIds(user.getId()+","+loginUser.getId());
			 sysAnnouncementController.add(sysAnnouncement);
			 // 查询通知公告
			 sysAnnouncement = new SysAnnouncement();
			 //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
			 if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
				 sysAnnouncement.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
			 }
			 sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
			 sysAnnouncement.setSendStatus(CommonConstant.DEL_FLAG_0.toString());
			 Map<String, String[]> parameterMap = new HashMap<>();
			 QueryWrapper<SysAnnouncement> queryWrapper = QueryGenerator.initQueryWrapper(sysAnnouncement, parameterMap);

			 Page<SysAnnouncement> page = new Page<SysAnnouncement>(1, 10);
			 IPage<SysAnnouncement> pageList = sysAnnouncementService.page(page, queryWrapper);
			 for(SysAnnouncement announcement : pageList.getRecords()){
				 sysAnnouncementController.doReleaseData(announcement.getId(),req);
			 }
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateMain(workOrder,workOrderPage.getWorkOrderProcessList());
		 return Result.OK("转派成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "服务记录-通过主表ID查询")
	 @ApiOperation(value="服务记录-通过主表ID查询", notes="服务记录-通过主表ID查询")
	 @GetMapping(value = "/queryWorkServiceRecordsByMainId")
	 public Result<IPage<CrmWorkServiceRecords>> queryWorkServiceRecordsListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<CrmWorkServiceRecords> workServiceRecordsList = workServiceRecordsService.selectByMainId(id);
		 IPage <CrmWorkServiceRecords> page = new Page<>();
		 page.setRecords(workServiceRecordsList);
		 page.setTotal(workServiceRecordsList.size());
		 return Result.OK(page);
	 }

	 /**
	  *  添加服务记录
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-编辑")
	 @ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
	 @RequiresPermissions("work:work_order:edit")
	 @RequestMapping(value = "/editServiceRecords", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editServiceRecords(@RequestBody CrmWorkOrderPage workOrderPage) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(8); // 服务记录
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"添加服务记录，内容："+workOrderPage.getWorkServiceRecordsList().get(0).getServiceContent());
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);
		 workOrderService.updateServiceRecords(workOrder, workOrderPage.getWorkServiceRecordsList(), workOrderPage.getWorkOrderProcessList());
		 return Result.OK("编辑成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工单回执-通过主表ID查询")
	 @ApiOperation(value="工单回执-通过主表ID查询", notes="工单回执-通过主表ID查询")
	 @GetMapping(value = "/queryWorkOrderReceiptByMainId")
	 public Result<IPage<CrmWorkOrderReceipt>> queryWorkOrderReceiptListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<CrmWorkOrderReceipt> workOrderReceiptList = workOrderReceiptService.selectByMainId(id);
		 IPage <CrmWorkOrderReceipt> page = new Page<>();
		 page.setRecords(workOrderReceiptList);
		 page.setTotal(workOrderReceiptList.size());
		 return Result.OK(page);
	 }
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "工单回访-通过主表ID查询")
	 @ApiOperation(value="工单回访-通过主表ID查询", notes="工单回访-通过主表ID查询")
	 @GetMapping(value = "/queryFollowUpByMainId")
	 public Result<IPage<CrmFollowUp>> queryFollowUpListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<CrmFollowUp> followUpList = followUpService.selectByMainId(id);
		 IPage <CrmFollowUp> page = new Page<>();
		 page.setRecords(followUpList);
		 page.setTotal(followUpList.size());
		 return Result.OK(page);
	 }

	 /**
	  *  添加回访记录
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-编辑")
	 @ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
	 @RequiresPermissions("work:work_order:edit")
	 @RequestMapping(value = "/editFollowUp", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editFollowUp(@RequestBody CrmWorkOrderPage workOrderPage) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 // 待回访状态改为已回访
		 workOrder.setWorkOrderStatus(13);

		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(7); // 已回访
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"添加回访记录，内容："+workOrderPage.getFollowUpList().get(0).getOverview());
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);

		 workOrderService.updateFollowUp(workOrder, workOrderPage.getFollowUpList(), workOrderPage.getWorkOrderProcessList());
		 return Result.OK("添加回访记录成功!");
	 }

	 /**
	  *  工单回执
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-编辑")
	 @ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
	 @RequiresPermissions("work:work_order:edit")
	 @RequestMapping(value = "/editWorkOrderReceipt", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editWorkOrderReceipt(@RequestBody CrmWorkOrderPage workOrderPage) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 // 待审核
		 workOrder.setWorkOrderStatus(9);
		 workOrder.setFinishTime(new Date()); // 完成时间
		 List<CrmWorkOrderProcess> workOrderProcessList = new ArrayList<>();
		 CrmWorkOrderProcess workOrderProcess = new CrmWorkOrderProcess();
		 workOrderProcess.setStatus(6); // 已处理
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser!=null){
			 workOrderProcess.setContent(sysUser.getRealname()+"已处理，回执内容："+workOrderPage.getWorkOrderReceiptList().get(0).getFailureCause());
		 }
		 workOrderProcessList.add(workOrderProcess);
		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);

		 workOrderService.updateWorkOrderReceipt(workOrder, workOrderPage.getWorkOrderReceiptList(), workOrderPage.getWorkOrderProcessList());
		 return Result.OK("添加工单回执成功!");
	 }

	 /**
	  *  审核回执
	  *
	  * @param workOrderPage
	  * @return
	  */
	 @AutoLog(value = "工单信息-编辑")
	 @ApiOperation(value="工单信息-编辑", notes="工单信息-编辑")
	 @RequiresPermissions("work:work_order:edit")
	 @RequestMapping(value = "/receiptReview", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> receiptReview(@RequestBody CrmWorkOrderPage workOrderPage) {
		 CrmWorkOrder workOrder = new CrmWorkOrder();
		 BeanUtils.copyProperties(workOrderPage, workOrder);
		 CrmWorkOrder workOrderEntity = workOrderService.getById(workOrder.getId());
		 if(workOrderEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 // 待回访
		 workOrder.setWorkOrderStatus(12);

//		 List<WorkOrderProcess> workOrderProcessList = new ArrayList<>();
//		 WorkOrderProcess workOrderProcess = new WorkOrderProcess();
//		 workOrderProcess.setStatus(6); // 已处理
//		 //获取登录用户信息
//		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		 if(sysUser!=null){
//			 workOrderProcess.setContent(sysUser.getRealname()+"已处理，回执内容："+workOrderPage.getWorkOrderReceiptList().get(0).getFailureCause());
//		 }
//		 workOrderProcessList.add(workOrderProcess);
//		 workOrderPage.setWorkOrderProcessList(workOrderProcessList);

		 workOrderService.receiptReview(workOrder, workOrderPage.getWorkOrderReceiptList(), workOrderPage.getWorkOrderProcessList());
		 return Result.OK("审核回执成功!");
	 }

	 /**
	  * 查询各状态下工单数
	  *
	  * @return
	  */
	 //@AutoLog(value = "工单信息-通过id查询")
	 @ApiOperation(value="查询各状态下工单数", notes="查询各状态下工单数")
	 @GetMapping(value = "/statistics")
	 public Result<CrmWorkOrderStatistics> statistics(@RequestParam(name="userFlag",required=true) Integer userFlag) {
		 CrmWorkOrderStatistics workOrder;
		 if(userFlag==0){
			 workOrder = workOrderService.statistics();
		 }else{
			 //获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 workOrder = workOrderService.statistics(sysUser.getUsername());
		 }
//		 WorkOrderStatistics workOrder = workOrderService.statistics();
		 if(workOrder==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(workOrder);

	 }
}
